package com.mingben.betplatform.util;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ExcelUtil {
    public static String EXCEL_XLS = "xls";
    public static String EXCEL_XLSX = "xlsx";

    // 去读Excel的方法readExcel，该方法的入口参数为一个File对象
    public static String readExcel(String path) {
        StringBuffer result = new StringBuffer();
        try {
            // jxl提供的Workbook类
            Workbook wb = getWorkbok(new File(path));
            // Excel的页签数量
            int sheet_size = wb.getNumberOfSheets();

            for (int index = 0; index < sheet_size; index++) {
                List<List> outerList=new ArrayList<List>();
                // 每个页签创建一个Sheet对象
                Sheet sheet = wb.getSheetAt(index);
                // sheet.getRows()返回该页的总行数
                for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum(); i++) {
                    List innerList=new ArrayList();
                    // sheet.getColumns()返回该页的总列数
                    Row row = sheet.getRow(i);
                    Iterator<Cell> cells = row.cellIterator();
                    while(cells.hasNext()) {
                        Cell cell = cells.next();
                        if(StringUtils.isNotEmpty(cell.getStringCellValue())){
                            result.append(cell.getStringCellValue());
                        }
                    }
                }
                return result.toString();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }



    /**
     * 判断Excel的版本,获取Workbook
     * @return
     * @throws IOException
     */
    public static Workbook getWorkbok(File file) throws IOException{
        Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if(file.getName().endsWith(EXCEL_XLS)){     //Excel&nbsp;2003
            wb = new HSSFWorkbook(in);
        }else if(file.getName().endsWith(EXCEL_XLSX)){    // Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }


}